package com.alipay.rebate.shop.scheduler.orderimport;

import com.alipay.rebate.shop.constants.ActivityConstant;
import com.alipay.rebate.shop.constants.OrdersConstant;
import com.alipay.rebate.shop.constants.TaskSettingsConstant;
import com.alipay.rebate.shop.constants.UserIncomeConstant;
import com.alipay.rebate.shop.dao.mapper.ActivityBrowseProductMapper;
import com.alipay.rebate.shop.dao.mapper.ActivityProductMapper;
import com.alipay.rebate.shop.dao.mapper.CommissionFreezeLevelSettingsMapper;
import com.alipay.rebate.shop.dao.mapper.CommissionLevelSettingsMapper;
import com.alipay.rebate.shop.dao.mapper.CouponGetRecordMapper;
import com.alipay.rebate.shop.dao.mapper.InviteSettingsMapper;
import com.alipay.rebate.shop.dao.mapper.OrderActivityRecordMapper;
import com.alipay.rebate.shop.dao.mapper.OrdersMapper;
import com.alipay.rebate.shop.dao.mapper.TaskSettingsMapper;
import com.alipay.rebate.shop.dao.mapper.UserGradeMapper;
import com.alipay.rebate.shop.dao.mapper.UserIncomeMapper;
import com.alipay.rebate.shop.dao.mapper.UserMapper;
import com.alipay.rebate.shop.helper.AppSettingsHelper;
import com.alipay.rebate.shop.helper.IncomeCommissionFreezeLevelHelper;
import com.alipay.rebate.shop.helper.LuckyMoneyHelper;
import com.alipay.rebate.shop.helper.UserHelper;
import com.alipay.rebate.shop.helper.UserIncomeBuilder;
import com.alipay.rebate.shop.helper.UserIncomeHelper;
import com.alipay.rebate.shop.model.ActivityBrowseProduct;
import com.alipay.rebate.shop.model.ActivityProduct;
import com.alipay.rebate.shop.model.AppSettings;
import com.alipay.rebate.shop.model.CommissionFreezeLevelSettings;
import com.alipay.rebate.shop.model.CommissionLevelSettings;
import com.alipay.rebate.shop.model.InviteSettings;
import com.alipay.rebate.shop.model.OrderActivityRecord;
import com.alipay.rebate.shop.model.Orders;
import com.alipay.rebate.shop.model.TaskSettings;
import com.alipay.rebate.shop.model.User;
import com.alipay.rebate.shop.model.UserGrade;
import com.alipay.rebate.shop.model.UserIncome;
import com.alipay.rebate.shop.pojo.taobao.TkOrderRsponse;
import com.alipay.rebate.shop.scheduler.AwardGradValue;
import com.alipay.rebate.shop.scheduler.TaobaoOrdersTkStatusMapper;
import com.alipay.rebate.shop.scheduler.TypeTkStatus;
import com.alipay.rebate.shop.utils.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

public abstract class AbstractOrdersImporter {

  private Logger logger = LoggerFactory.getLogger(AbstractOrdersImporter.class);
  private Long ACTIVITY_ADZONE_ID = 65516450421L;
  @Resource
  OrdersMapper ordersMapper;
  @Resource
  UserMapper userMapper;
  @Resource
  UserIncomeMapper userIncomeMapper;
  @Resource
  UserGradeMapper userGradeMapper;
  @Resource
  ActivityProductMapper activityProductMapper;
  @Resource
  ActivityBrowseProductMapper activityBrowseProductMapper;
  @Resource
  InviteSettingsMapper inviteSettingsMapper;
  @Resource
  OrderActivityRecordMapper orderActivityRecordMapper;
  @Resource
  TaskSettingsMapper taskSettingsMapper;
  @Resource
  CouponGetRecordMapper couponGetRecordMapper;
  @Resource
  LuckyMoneyHelper luckyMoneyHelper;
  @Resource
  UserHelper userHelper;
  @Resource
  UserIncomeHelper userIncomeHelper;
  @Resource
  CommissionLevelSettingsMapper commissionLevelSettingsMapper;
  @Resource
  CommissionFreezeLevelSettingsMapper commissionFreezeLevelSettingsMapper;
  @Resource
  IncomeCommissionFreezeLevelHelper incomeCommissionFreezeLevelHelper;

  Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();

  public void importOrders(String startTime,String endTime, TypeTkStatus tkStatus){
    // 从第一页开始， 页面大小使用默认值
    Long pageNo = 1L;
    String positionIndex = null;
    // 导入渠道付款订单
    while(true){
      TkOrderRsponse rsp = TaobaoUtil.getOrdersByStatusAndType(
          tkStatus,startTime,endTime,pageNo,positionIndex
      );
//      TkOrderRsponse rsp = TestUtil.test(1);
      logger.debug("Paid TkOrderRsponse relation is : {}",rsp);
      pageNo ++;
      positionIndex = rsp.getPosition_index();
      logger.debug("pageNo and positionIndex is : {}",pageNo,positionIndex);
      // 处理渠道订单
      processTkOrderRsponse(rsp,tkStatus);
      if(isDone(rsp)) break;
//      break;
    }
  }

  public void importPaidAndAccountingOrders(String startTime, LocalDateTime finalEndTime,TypeTkStatus typeTkStatus)
      throws InterruptedException {

    logger.debug("importPaidAndAccountingOrders, startTime is : {}",startTime);
    LocalDateTime nextStartLocationTime = null;
    AppSettings appSettings = AppSettingsHelper.getAppSettings();
    int importMinutes = appSettings.getTaobaoAmImportTimeArea();
    if(importMinutes < 20){
      importMinutes = 20;
    }
    do{
      String endTime = getMinutesLater(startTime, importMinutes);
      importOrders(startTime,endTime,typeTkStatus);
      nextStartLocationTime = DateUtil.getLocationDateTime(startTime);
      startTime = endTime;
      Thread.sleep(100);
    }while (nextStartLocationTime.isBefore(finalEndTime));
  }


  public void importOverDueOrders(String startTime,LocalDateTime finalEndTime, TypeTkStatus tkStatus)
      throws InterruptedException {
    LocalDateTime nextStartLocationTime = null;
    AppSettings appSettings = AppSettingsHelper.getAppSettings();
    int importMinutes = appSettings.getTaobaoAmImportTimeArea();
    if(importMinutes < 20){
      importMinutes = 20;
    }
    do{

      String endTime = getMinutesLater(startTime, importMinutes);
      logger.debug("startTime and endTime:{},{}",startTime,endTime);
      Long pageNo = 1L;
      String positionIndex = null;
      // 导入渠道付款订单
      while(true){
        TkOrderRsponse rsp = TaobaoUtil.getOrdersByStatusAndType(
            tkStatus,startTime,endTime,pageNo,positionIndex
        );
        logger.debug("OD TkOrderRsponse special is : {}",rsp);
        pageNo ++;
        positionIndex = rsp.getPosition_index();
        logger.debug("OD pageNo and positionIndex is : {}",pageNo,positionIndex);
        // 处理渠道订单
        processTkOrderRsponse(rsp,tkStatus);
        if(isDone(rsp)) break;
      }

      nextStartLocationTime = DateUtil.getLocationDateTime(endTime);
      startTime = endTime;
      Thread.sleep(100);
    }while (nextStartLocationTime.isBefore(finalEndTime));
  }

  private void processTkOrderRsponse(TkOrderRsponse rsp, TypeTkStatus tkStatus){
    switch (tkStatus){
      case RELATION_PAID:
      case RELATION_ACCOUNTING:
      case RELATION_COMPLETE:
      case RELATION_OVERDUE:
        processRelationTkOrderRsponse(rsp);
        break;
      case NORMAL_PAID:
      case NORMAL_ACCOUNTING:
      case NORMAL_COMPLETE:
      case NORMAL_OVERDUE:
        processNormalTkOrderRsponse(rsp);
        break;
      case SPECIAL_PAID:
      case SPECIAL_ACCOUNTING:
      case SPECIAL_COMPLETE:
      case SPECIAL_OVERDUE:
        processSpecialTkOrderRsponse(rsp);
        break;
    }
  }

  public void processRelationTkOrderRsponse(TkOrderRsponse rsp){
    if(rsp.getData() == null) return;
    logger.debug("processRelationTkOrderRsponse rsp is : {}",rsp);
    rsp.getData().forEach(orders -> {
      logger.debug("Relation Start <--------------------> Start");
      // 根据订单号查询出数据库订单
      Orders previousOrder = ordersMapper.selectTradeIdAndTkStatus(orders.getTradeId());
      // 获取先前的订单
      logger.debug("Relation previousOrder is : {}",previousOrder);
      // 如果订单状态和数据库订单状态一样，那么不处理
      if(existsInDbAndStatusTheSame(orders,previousOrder)){
        // 如果订单未处理过，则进行处理
//        if (previousOrder.getIsRecord() == 0){
//          logger.debug("is_record is : {}",previousOrder.getIsRecord());
//          orders.setIsRecord(1);
//          dealWithRelationOrders(orders,previousOrder);
//          return;
//        }
//        handleWhenPreviousOrderExists(orders,previousOrder);
        logger.debug("orders have inserted");
        return;
      }

      if (previousOrder != null) {
        if (previousOrder.getIsRecord() == 2) {
          // 用户自己找回的订单
          orders.setIsRecord(previousOrder.getIsRecord());
          handleWhenPreviousOrderExists(orders, previousOrder);
          logger.debug("Relation End <--------------------> End");
          return;
        }
      }

      // 如果relationId 为空，那么保存/更新订单即可
      if(orders.getRelationId() == null){
        orders.setIsRecord(0);
        saveOrUpdateOrders(orders,previousOrder);
        logger.debug("Relation End <--------------------> End");
        return;
      }
      // 先前已经导入状态不同订单
      if(previousOrder != null){
        handleWhenPreviousOrderExists(orders,previousOrder);
        logger.debug("Relation End <--------------------> End");
        return;
      }

      dealWithRelationOrders(orders,null);
      logger.debug("Relation End <--------------------> End");
    });
  }

  public void processNormalTkOrderRsponse(TkOrderRsponse rsp){
    if(rsp.getData() == null) return;
    rsp.getData().forEach(orders -> {
      logger.debug("Relation orders");

      if (checkIfTradeEqualsRelationOrSpecialId(orders)){
        logger.debug("orders is relation or special");
        return;
      }

      logger.debug("Normal Start <--------------------> Start");
      // 根据订单号查询出数据库订单
      Orders previousOrder = ordersMapper.selectTradeIdAndTkStatus(orders.getTradeId());
      // 获取先前的订单
      logger.debug("Normal previousOrder is : {}",previousOrder);
      // 如果订单状态和数据库订单状态一样，那么不处理
      if(existsInDbAndStatusTheSame(orders,previousOrder)){
        logger.debug("orders have inserted");
        // 相同订单状态也要处理，因为会出现预售订单，前后的预估佣金不一致
//        handleWhenPreviousOrderExists(orders,previousOrder);
        return;
      }
      // 先前已经导入状态不同订单
      if(previousOrder != null){
        if (previousOrder.getIsRecord() == 2){
          orders.setIsRecord(2);
        }
        handleWhenPreviousOrderExists(orders,previousOrder);
        logger.debug("Normal End <--------------------> End");
        return;
      }

      // 如果根据淘宝id查询出来的用户超过两个，直接入库
      if(checkIfUserFindbyTbidMoreThanTwoAndDoLogic(orders)){
        logger.debug("Relation End <--------------------> End");
        return;
      }


      dealWithNormalOrders(orders,null);
      logger.debug("Normal End <--------------------> End");
    });
  }

  private Boolean checkIfTradeEqualsRelationOrSpecialId(Orders orders){
    logger.debug("orders tkPaidTime is and tkStatus : {}",orders.getTkStatus(),orders.getTkStatus());
    String time = null;
    try {
      SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date parse = df.parse(orders.getTkPaidTime());
      time = df.format(parse);
    } catch (ParseException e) {
      logger.error(""+e);
    }
    String startTime = DateUtil.getTkPaidTimeBeforeOrAfter(time,10);
    String endTime = DateUtil.getTkPaidTimeBeforeOrAfter(time,-10);
    TkOrderRsponse response1 = TaobaoUtil.getOrdersByStatusAndType(TaobaoOrdersTkStatusMapper.getRelationTkStatus(orders.getTkStatus()),
            startTime, endTime, 1L, null);
    if (compareTradeId(response1, orders)){
      logger.debug("this orders is Relation , should import by Relation");
      return true;
    }
    TkOrderRsponse response2 = TaobaoUtil.getOrdersByStatusAndType(TaobaoOrdersTkStatusMapper.getSpecialTkStatus(orders.getTkStatus()),
            startTime, endTime, 1L, null);
    if (compareTradeId(response2,orders)){
      logger.debug("this orders is Special , should import by Special");
      return true;
    }
    return false;
  }

  private Boolean compareTradeId(TkOrderRsponse response,Orders orders){
    logger.debug("compareTradeId data is : {}",response.getData());
    logger.debug("compareTradeId orders is : {}",orders);
    if (response != null && !ListUtil.isEmptyList(response.getData())) {
      List<Orders> result = response.getData();
      for (Orders data : result) {
        if (orders.getTradeId().equals(data.getTradeId())){
          logger.debug("orders trade and datum trade_id is : {},{}",orders.getTradeId(),data.getTradeId());
          return true;
        }
      }
    }
    return false;
  }

  public void processSpecialTkOrderRsponse(TkOrderRsponse rsp){
    if(rsp.getData() == null) return;
    rsp.getData().forEach(orders -> {
      logger.debug("Special Start <--------------------> Start");
      // 根据订单号查询出数据库订单
      Orders previousOrder = ordersMapper.selectTradeIdAndTkStatus(orders.getTradeId());
      // 获取先前的订单
      logger.debug("Special previousOrder is : {}",previousOrder);
      // 如果订单状态和数据库订单状态一样，那么不处理
      if(existsInDbAndStatusTheSame(orders,previousOrder)){
        logger.debug("orders have inserted");
        // 相同订单状态也要处理，因为会出现预售订单，前后的预估佣金不一致，已后面的预估佣金为准
//        handleWhenPreviousOrderExists(orders,previousOrder);
        return;
      }

      // 先前已经导入状态不同订单
      if(previousOrder != null){
        if (previousOrder.getIsRecord() == 2){
          orders.setIsRecord(2);
        }
        handleWhenPreviousOrderExists(orders,previousOrder);
        logger.debug("Special End <--------------------> End");
        return;
      }

      // 如果根据淘宝id查询出来的用户超过两个，直接入库
//      if(checkIfUserFindbyTbidMoreThanTwoAndDoLogic(orders)){
//        logger.debug("Relation End <--------------------> End");
//        return;
//      }

      dealWithSpecialOrders(orders,null);
      logger.debug("Special End <--------------------> End");
    });
  }

  private void handleWhenPreviousOrderExists(Orders orders, Orders previousOrder){

    // 如果先前导入的是入库非确定订单，那么只需要简单更新
    if(Integer.valueOf(0).equals(previousOrder.getIsRecord())){
      ordersMapper.updateByPrimaryKeySelective(orders);
      return;
    }

    // 从数据库订单拷贝一些数据
    orders.setUserId(previousOrder.getUserId());
    orders.setUserUit(previousOrder.getUserUit());
    orders.setUserCommission(previousOrder.getUserCommission());
    orders.setOneLevelUserUit(previousOrder.getOneLevelUserUit());
    orders.setOneLevelCommission(previousOrder.getOneLevelCommission());
    orders.setTwoLevelUserUit(previousOrder.getTwoLevelUserUit());
    orders.setTwoLevelCommission(previousOrder.getTwoLevelCommission());
    orders.setPromoterId(previousOrder.getPromoterId());
    orders.setPromoterName(previousOrder.getPromoterName());
    orders.setActivityId(previousOrder.getActivityId());
    // 淘宝客联盟导入失效渠道订单或者会员运营订单时有时候不返回渠道id或者会员运营id，坑
    orders.setRelationId(previousOrder.getRelationId());
    orders.setSpecialId(previousOrder.getSpecialId());

    // 获取用户信息
    Long parentUserId , parentPUserId = null;
    User user, oneLevelUser = null;

    // 如果是渠道订单，那么奖励是按照推广人，推广人上级，推广人上上级进行奖励的
    if(orders.getRelationId() != null){
      user = userMapper.selectUserByRelationId(orders.getRelationId());
    }else{ // 常规订单或者会员运营订单
      user = userMapper.selectById(orders.getUserId());
    }

    // 没查询到用户，说明是用户自己找回的订单，之前已为用户处理过
    // 以前的订单携带有用户信息
    if (user == null){
      logger.debug("handleWhenPreviousOrderExists user is null");
      try {
        ordersMapper.updateByPrimaryKeySelective(orders);
        User user1 = null;
        user1 = userMapper.selectById(previousOrder.getUserId());
        // 用户自己找回的订单，userId可能为空，promoterId不为空
        if (user1 == null){
          user1 = userMapper.selectById(previousOrder.getPromoterId());
        }
        parentUserId = user1.getParentUserId();
        if (parentUserId != null) {
          oneLevelUser = userMapper.selectById(parentUserId);
          parentPUserId = oneLevelUser.getParentUserId();
        }
        if (orders.getTkStatus() == OrdersConstant.ACCOUNTING_STATUS){
          // 查询订单的收益明细状态，
          UserIncome userIncome = userIncomeMapper.selectUserIncomeByTradeIdAndStatus(orders.getTradeId());
          if (userIncome != null) {
            logger.debug("orders is : {}",orders);
            logger.debug("previousOrder is : {}",previousOrder);
            // 订单结算状态
            logger.debug("parentUserId, parentPuserId is : {},{}", parentUserId, parentPUserId);
            logger.debug("user, oneLevelUser is : {}", user, oneLevelUser);
            doDealWithOrder(orders, previousOrder, parentUserId, parentPUserId, user1, oneLevelUser);
          }
        }
      }catch (Exception e){
        logger.error(""+e);
      }
      return;
    }

    // 正常订单
    if (user != null) {
      parentUserId = user.getParentUserId();
      if (parentUserId != null) {
        oneLevelUser = userMapper.selectById(parentUserId);
        parentPUserId = oneLevelUser.getParentUserId();
      }
      logger.debug("parentUserId, parentPuserId is : {},{}", parentUserId, parentPUserId);
      logger.debug("user, oneLevelUser is : {}", user, oneLevelUser);
      doDealWithOrder(orders, previousOrder, parentUserId, parentPUserId, user, oneLevelUser);
    }
  }

  private boolean checkIfUserFindbyTbidMoreThanTwoAndDoLogic(Orders orders){
    String tbId = getTaobaoUserIdFinalSixNumber(orders.getTradeId());
    int uCount = userMapper.selectCountByTbid(tbId);
    if(uCount >=2){
      orders.setIsRecord(0);
      saveOrUpdateOrders(orders,null);
      logger.debug("End <--------------------> End");
      return true;
    }
    return false;
  }
  private boolean isDone(TkOrderRsponse rsp){
    return ListUtil.isEmptyList(rsp.getData()) ||
        (rsp.getHas_next() != null && !rsp.getHas_next());
  }

  private String getTwentyMinutesLater(String startTime){
    LocalDateTime localDateTime = DateUtil.getLocationDateTime(startTime);
    // 获取 20 分钟后的时间
    String endTime = DateUtil.getTwentyMinutesAfter(localDateTime);
    logger.debug("startTime and endTime is : {},{}",startTime,endTime);
    return endTime;
  }

  private String getMinutesLater(String startTime, int minutes){
    LocalDateTime localDateTime = DateUtil.getLocationDateTime(startTime);
    // 获取 20 分钟后的时间
    String endTime = DateUtil.getMinutesAfter(localDateTime, minutes);
    logger.debug("startTime and endTime is : {},{}",startTime,endTime);
    return endTime;
  }


  /**
   * 处理渠道订单
   * @param orders
   */
  @Transactional
  public void dealWithRelationOrders(Orders orders, Orders previousOrder){

    String pid = concatPid(orders);
    logger.debug("pid is : {}",pid);
    // TODO (no need to get second times , refactor later)
    AppSettings appSettings = AppSettingsHelper.getAppSettings();
    if(!pid.equals(appSettings.getPid()) && !pid.equals(appSettings.getActivityPid())){
      logger.debug("do not equal to any pid in db");
      return;
    }

    logger.debug("orders is : {}",orders);
    // 如果relationId 为空，那么保存订单即可
    if(orders.getRelationId() == null){
      orders.setIsRecord(0);
      saveOrUpdateOrders(orders,previousOrder);
      return;
    }

    // 生成淘宝id后六位数字
    List<User> userList = getUserByTbIdFinalSixNumber(orders);
//    User user = getUserByTbId(orders);
    logger.debug("userList is and userList size : {},{}",userList,userList.size());
    // 根据relationId 获取用户信息
    User relationIdUser = userMapper.selectUserByRelationId(orders.getRelationId());
    logger.debug("relationId user is : {}",relationIdUser);
    Long relationUserId = relationIdUser == null ? null : relationIdUser.getUserId();
    if(userList == null || userList.size() >= 2 || userList.size() == 0){
      logger.debug("Not our platform user");
      // 购买商品的不是我们平台的用户，则查看推广人是否是我们平台的用户
      // 如果relationId 为空，说明推广人也不是我们平台的，丢弃这个订单
      if(relationUserId == null){
        logger.debug("RelationId user not our platform user");
        orders.setIsRecord(0);
        saveOrUpdateOrders(orders,previousOrder);
        return;
      }
      // 如果推广人是我们平台的，那么保存订单
      setOrdersInfoWhenRelationNewImport(orders,
          null, null,
          relationUserId,
          relationIdUser.getUserNickName());
      // 进入订单处理逻辑
      doDealWithRltOrder(orders,relationIdUser,null,
          relationIdUser.getParentUserId(),previousOrder);
    }else{
      logger.debug("our platform user");
      // 如果relationId 为空，说明推广人不是我们平台的，丢弃这个订单
      if(relationUserId == null){
        logger.debug("relationIdUser is not our platform user");
        orders.setIsRecord(0);
        saveOrUpdateOrders(orders,previousOrder);
        return;
      }

      for (User user : userList) {
        // 购买商品的是我们平台的用户
        if(user.getUserId().equals(relationUserId)){
          // 如果商品就是推广人自己购买的，那么保存订单
          logger.debug("user and relationIdUser is the same");
          setOrdersInfoWhenRelationNewImport(orders,
                  user.getUserId(),
                  user.getUserNickName(),
                  relationUserId,
                  relationIdUser.getUserNickName());
          doDealWithRltOrder(orders,relationIdUser,null,
                  user.getParentUserId(),previousOrder);
          return;
        }
        // 如果推广人和购买人都是我们平台的，那么保存订单
        logger.debug("relationIdUser and user is not the same");
        // 订单数加 1
        setOrdersInfoWhenRelationNewImport(orders,
                user.getUserId(),
                user.getUserNickName(),
                relationUserId,
                relationIdUser.getUserNickName());
        doDealWithRltOrder(orders,relationIdUser,
                null,relationIdUser.getParentUserId(),previousOrder);
      }

    }
  }

  private void setOrdersInfoWhenRelationNewImport(
      Orders orders,
      Long userId,
      String userName,
      Long relationUserId,
      String relationUserName
      ){
    orders.setUserId(userId);
    orders.setUserName(userName);
    orders.setPromoterId(relationUserId);
    orders.setPromoterName(relationUserName);
  }

  /**
   * 处理常规订单
   * @param orders
   */
  @Transactional
  public void dealWithNormalOrders(Orders orders, Orders previousOrder){

    if(orders == null) return ;

    AppSettings appSettings = AppSettingsHelper.getAppSettings();
    String pid = appSettings.getPid();
    String acPid = appSettings.getActivityPid();
    String adzoneid = pid.substring(pid.lastIndexOf("_") + 1);
    String acAdzoneid = acPid.substring(acPid.lastIndexOf("_") + 1);
    String orderZoneid = String.valueOf(orders.getAdzoneId());
    logger.debug("adzoneid acAdzoneid orderZoneid is : {},{},{}",adzoneid,acAdzoneid,orderZoneid);
    if(!orderZoneid.equals(adzoneid) && !orderZoneid.equals(acAdzoneid)){
      logger.debug("do not equal to any pid in db");
      return;
    }

    // 根据淘宝id 获取用户
    User user = getUserByTbId(orders);
    // 如果用户不是我们平台的， 直接返回
    if(user == null){
      orders.setIsRecord(0);
      ordersMapper.insertSelective(orders);
      return;
    }
    orders.setUserId(user.getUserId());
    orders.setUserName(user.getUserNickName());
    doDealWithNMOrder(orders,user,previousOrder);
  }

  /**
   * 处理会员运营订单
   * @param orders
   */
  @Transactional
  public void dealWithSpecialOrders(Orders orders, Orders previousOrder){

    logger.debug("Special Orders is : {}",orders);
    // 根据specialId 获取用户
    User user = userMapper.selectUserByRelationIdOrSpecialId(null,orders.getSpecialId());
    // 如果用户不是我们平台的， 直接返回
    if(user == null){
      orders.setIsRecord(0);
      ordersMapper.insertSelective(orders);
      return;
    }
    orders.setUserId(user.getUserId());
    orders.setUserName(user.getUserNickName());
    doDealWithSCOrder(orders,user,previousOrder);
  }


  private User getUserByTbId(Orders orders){
    String tradeIdStr = String.valueOf(orders.getTradeId());
    String taobaoUserIdFinalSixNumber
        = getTaobaoUserIdFinalSixNumber(tradeIdStr);
    logger.debug("taobaoUserId finalSixNumber is : {}",taobaoUserIdFinalSixNumber);
    // 通过淘宝用户id到数据库查询用户，如果用户不为空，那么就是我们平台的用户
    return userMapper.selectUserInfoByTaobaoUserIdFinalSixNumber(taobaoUserIdFinalSixNumber);
  }

  private List<User> getUserByTbIdFinalSixNumber(Orders orders){
    String tradeIdStr = String.valueOf(orders.getTradeId());
    String taobaoUserIdFinalSixNumber
            = getTaobaoUserIdFinalSixNumber(tradeIdStr);
    logger.debug("taobaoUserId finalSixNumber is : {}",taobaoUserIdFinalSixNumber);
    return userMapper.selectUserByTaoBaoUserIdFinalSixNumber(taobaoUserIdFinalSixNumber);
  }

  private String getTaobaoUserIdFinalSixNumber(String tradeIdStr){
    Integer length = tradeIdStr.length();
    StringBuilder builder = new StringBuilder();
    builder.append(tradeIdStr.substring(length -6,length - 4));
    builder.append(tradeIdStr.substring(length -2,length));
    builder.append(tradeIdStr.substring(length -4,length - 2));
    return builder.toString();
  }

  public void doDealWithRltOrder(
      Orders orders,
      User user,
      User oneLevelUser,
      Long parentUserId,
      Orders previousOrder
  ){

    Long parentPUserId = null;
    // 上级用户
    if(oneLevelUser == null){
      oneLevelUser = userMapper.selectById(parentUserId);
    }
    // 获取父上上级用户id
    parentPUserId = getParentUserId(oneLevelUser);

    logger.debug("oneLevelUser is : {}",oneLevelUser);
    logger.debug("parentUserId and parentPUserId is : {},{}", parentUserId, parentPUserId);

    doDealWithOrder(orders,previousOrder,parentUserId,parentPUserId,user,oneLevelUser);

  }

  private Long getParentUserId(User user){
    if(user != null){
      return user.getParentUserId();
    }
    return null;
  }

  private User getParentUser(Long id){
    if(id != null){
      return userMapper.selectById(id);
    }
    return null;
  }

  public void doDealWithNMOrder(Orders orders , User user, Orders previousOrder){

    if(previousOrder != null && previousOrder.getRelationId() != null){
      // 如果数据库已经存在了渠道id订单, 那么直接返回不处理
      logger.debug("a relationId order is exists in database");
      return ;
    }
    if(previousOrder != null && previousOrder.getSpecialId() != null){
      // 如果数据库已经存在了会员id订单, 那么直接返回不处理
      logger.debug("a special order is exists in database");
      return ;
    }
    // 获取一级用户，二级用户信息
    User oneLevelUser = getParentUser(user.getParentUserId());
    Long parentUserId = user.getParentUserId();
    Long parentPUserId = getParentUserId(oneLevelUser);
    logger.debug("Normal parentUserId and parentPUserId is : {}",parentUserId,parentPUserId);
    doDealWithOrder(orders,previousOrder,parentUserId,parentPUserId,user,oneLevelUser);
  }

  public void doDealWithSCOrder(Orders orders , User user, Orders previousOrder){

    // 获取一级用户，二级用户信息
    User oneLevelUser = getParentUser(user.getParentUserId());
    Long parentUserId = user.getParentUserId();
    Long parentPUserId = getParentUserId(oneLevelUser);
    logger.debug("Special parentUserId and parentPUserId is : {}",parentUserId,parentPUserId);
    doDealWithOrder(orders,previousOrder,parentUserId,parentPUserId,user,oneLevelUser);
  }

  private boolean existsInDbAndStatusTheSame(Orders orders, Orders previousOrder){
    if(previousOrder != null && orders.getTkStatus().equals(previousOrder.getTkStatus())){
      logger.debug("orders have inserted");
      return true;
    }
    return false;
  }

   abstract void doDealWithOrder(
      Orders orders,
      Orders previousOrder,
      Long parentUserId,
      Long parentPUserId,
      User user,
      User oneLevelUser
  );

  protected BigDecimal getTotalGetMoney(Orders orders){
    BigDecimal totalGetMoney = new BigDecimal("0.00");
    // 如果是付款状态中的订单，那么按照佣金字段计算用户预估收益
    if(OrdersConstant.PAID_STATUS.equals(orders.getTkStatus())){
      logger.debug("tkStatus is : {}",OrdersConstant.PAID_STATUS);
      totalGetMoney = orders.getPubSharePreFee();
    }
    // 如果是结算状态中的订单，那么按照效果预估字段计算用户收益
    if(OrdersConstant.ACCOUNTING_STATUS.equals(orders.getTkStatus())){
      logger.debug("tkStatus is : {}",OrdersConstant.ACCOUNTING_STATUS);
      totalGetMoney = orders.getPubSharePreFee();
    }
    // 如果是结算状态中的订单，那么按照效果预估字段计算用户收益
    if(OrdersConstant.COMPLETE_STATUS.equals(orders.getTkStatus())){
      logger.debug("tkStatus is : {}",OrdersConstant.COMPLETE_STATUS);
      totalGetMoney = orders.getPubSharePreFee();
    }
    return totalGetMoney;
  }

  protected void dealwithActivityOrdersLogicIfis(
      Orders previousOrders,
      Orders orders,
      Long userId
  ){
    // 如果先前已经导入，就不需要再判断是哪种活动商品了
    if(previousOrders != null && previousOrders.getActivityId() != null) {
      logger.debug("previousOrders activityId: {}",previousOrders.getActivityId());
      orders.setActivityId(previousOrders.getActivityId());
      orders.setUserCommission(previousOrders.getUserCommission());
      orders.setUserUit(previousOrders.getUserUit());
      return;
    }

    Long adzoneId = orders.getAdzoneId();
    // 说明是活动订单
    if(AppSettingsHelper.getActivityAdzoneId().equals(String.valueOf(adzoneId))){
      // 获取活动商品浏览记录
      String clickTime = orders.getClickTime();
      LocalDateTime clickLocalTime = DateUtil.getLocationDateTime(clickTime);
      LocalDateTime tMBLocalTime = clickLocalTime.minusMinutes(2);
      DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
      String twoMinuteBefore = tMBLocalTime.format(fmt);
      logger.debug("activity product startTime and endTime is : {},{}",
          twoMinuteBefore,clickTime);
      List<ActivityBrowseProduct> productList = activityBrowseProductMapper
          .getByProductIdAndTime(String.valueOf(orders.getNumIid()),twoMinuteBefore,clickTime,userId);
      logger.debug("productList is : {}",productList);
      // 如果2分钟内并没有点击活动商品,那么当作正常订单处理
      if(ListUtil.isEmptyList(productList)){
        return;
      }

      ActivityBrowseProduct activityBrowseProduct = productList.get(0);
      logger.debug("ActivityBrowseProduct is : {}",activityBrowseProduct);
      int activityId = activityBrowseProduct.getActivityId();

      // 0 元购活动
      if(activityId == ActivityConstant.ZERO_PURCHASE_ACTIVITY){
        ActivityProduct activityProduct = activityProductMapper
            .selectProductByActivityAndProductId(activityId,String.valueOf(orders.getNumIid()));

        if(activityProduct == null){
          logger.debug("now activityProduct found");
          return;
        }

        // 用户实际获取金额
        orders.setUserCommission(activityProduct.getRefundsPrice());
        Long userUit = activityProduct.getRefundsPrice()
            .multiply(new BigDecimal("100")).longValue();
        orders.setUserUit(userUit);

        // 活动订单记录
        OrderActivityRecord orderActivityRecord = new OrderActivityRecord();
        orderActivityRecord.setActivityId(activityId);
        orderActivityRecord.setActivityProductId(activityProduct.getId());
        orderActivityRecord.setCreateTime(DateUtil.getNowStr());
        orderActivityRecord.setQualType(activityProduct.getQualType());
        orderActivityRecord.setUserId(userId);
        orderActivityRecord.setTradeId(orders.getTradeId());
        orderActivityRecordMapper.insertSelective(orderActivityRecord);
      }
      // 自定义密令活动
      if(activityId == ActivityConstant.CUSTOM_COMMAND_ACTIVITY){
        orders.setUserCommission(orders.getAlipayTotalPrice());
        orders.setUserUit(orders.getAlipayTotalPrice().multiply(new BigDecimal("100")).longValue());
        // 活动订单记录
        OrderActivityRecord orderActivityRecord = new OrderActivityRecord();
        orderActivityRecord.setActivityId(activityId);
        orderActivityRecord.setCreateTime(DateUtil.getNowStr());
        orderActivityRecord.setUserId(userId);
        orderActivityRecord.setTradeId(orders.getTradeId());
        orderActivityRecordMapper.insertSelective(orderActivityRecord);
      }

      orders.setOneLevelUserUit(0L);
      orders.setTwoLevelUserUit(0L);
      orders.setOneLevelCommission(new BigDecimal("0.00"));
      orders.setTwoLevelCommission(new BigDecimal("0.00"));
      orders.setActivityId(activityId);

    }
  }

  protected void countCommission(
      BigDecimal totalGetMoney,
      Orders orders,
      Long parentUserId,
      Long parentPUserId,
      User user,
      User parentUser
  ){
    logger.debug("countCommission orders trade_id is : {}",orders.getTradeId());
    // 如果是活动订单,那么不需要计算,因为之前已经根据活动商品表算过了
    if(orders.getActivityId() != null){
      return;
    }

    UserGrade userGrade = userGradeMapper.selectByPrimaryKey(user.getUserGradeId());
    Double firstLevelCommission = userGrade.getFirstCommission();
    Double secondLevelCommission = 0.00;
    Double thirdLevelCommission = 0.00;
    if(parentUserId != null){
      UserGrade ug = userGradeMapper.selectByPrimaryKey(parentUser.getUserGradeId());
      secondLevelCommission = ug.getSecondCommission();
    }
    if(parentPUserId != null){
      User parentPUser = userMapper.selectById(parentPUserId);
      UserGrade ug = userGradeMapper.selectByPrimaryKey(parentPUser.getUserGradeId());
      thirdLevelCommission = ug.getThirdCommission();
    }

    // 根据用户下单价格到佣金等级表进行查找
    List<CommissionLevelSettings> commissionLevelSettingses =
        commissionLevelSettingsMapper.selectByBeginAndEnd(totalGetMoney);
    logger.debug("commissionLevelSettingses is : {}",commissionLevelSettingses);

    if(!ListUtil.isEmptyList(commissionLevelSettingses)){
      List<CommissionLevelSettings> st1 = commissionLevelSettingses.stream()
          .filter(setting -> !userGrade.getId().equals(setting.getUserGradeId()))
          .collect(Collectors.toList());
      logger.debug("st1 is : {}",st1);
      // 如果用户等级佣金比例设置开启
      if(userGrade.getEnableCmlevelSettings() == 1){
        List<CommissionLevelSettings> st2 = commissionLevelSettingses.stream()
            .filter(setting -> userGrade.getId().equals(setting.getUserGradeId()))
            .collect(Collectors.toList());
         logger.debug("st2 is : {}",st2);

        if(!ListUtil.isEmptyList(st2)){
          st1 = st2;
        }
      }
      commissionLevelSettingses = st1;
    }

    // 如果佣金等级表存在多条适合条件记录（设置重叠情况），那么取第一条
    // 佣金等级表的佣金比例用户等级设置比率
    if (!ListUtil.isEmptyList(commissionLevelSettingses)){
      CommissionLevelSettings commissionLevelSettings = commissionLevelSettingses.get(0);
      firstLevelCommission = commissionLevelSettings.getRate().doubleValue();
    }

    logger.debug("one , two , three level commission rate is : {},{},{}",
        firstLevelCommission,secondLevelCommission,thirdLevelCommission);

    // 如果等级表的数据某一条为空,按照默认值设置
    firstLevelCommission = firstLevelCommission == null ? 100 : firstLevelCommission;
    secondLevelCommission = secondLevelCommission == null ? 0 : secondLevelCommission;
    thirdLevelCommission = thirdLevelCommission == null ? 0 : thirdLevelCommission;
    // 用户本人佣金
    BigDecimal userCommission =
        caculateCommission(totalGetMoney,firstLevelCommission);
    // 上级佣金
    BigDecimal oneLevelCommission =
        caculateCommission(totalGetMoney,secondLevelCommission);
    // 上上级佣金
    BigDecimal twoLevelCommission =
        caculateCommission(totalGetMoney,thirdLevelCommission);
    // 用户佣金可以直接设置
    orders.setUserCommission(userCommission);
    logger.debug("userCommission,oneLevelCommission,twoLevelCommission is : {},{},{}",
        userCommission,oneLevelCommission,twoLevelCommission);

    // 计算用户获取的积分宝，上级积分宝，上上级积分宝
    Long userUit = DecimalUtil.convertMoneyToUit(userCommission);
    Long oneLevelUit = DecimalUtil.convertMoneyToUit(oneLevelCommission);
    Long twoLevelUit = DecimalUtil.convertMoneyToUit(twoLevelCommission);
    orders.setUserUit(userUit);

    if(parentUserId != null){
      orders.setOneLevelCommission(oneLevelCommission);
      orders.setOneLevelUserUit(oneLevelUit);
    }

    if(parentPUserId != null){
      orders.setTwoLevelCommission(twoLevelCommission);
      orders.setTwoLevelUserUit(twoLevelUit);
    }
    logger.debug("userUit,oneLevelUit,twoLevelUit is : {},{},{}",
        userUit,oneLevelUit,twoLevelUit);
  }


  /**
   * 用BigDecimal 计算是避免精度丢失问题
   * @param totalGetMoney
   * @param commissionRate
   * @return
   */
  private BigDecimal caculateCommission(BigDecimal totalGetMoney, Double commissionRate){
    // 四舍五入
    BigDecimal bCimmissionRate = new BigDecimal(commissionRate)
        .setScale(OrdersConstant.SCALE,BigDecimal.ROUND_DOWN);
    // 除于100, 四舍五入
    bCimmissionRate = bCimmissionRate.divide(new BigDecimal("100"),BigDecimal.ROUND_DOWN)
        .setScale(OrdersConstant.SCALE,BigDecimal.ROUND_DOWN);
    // 乘于佣金比例等于用户所得佣金
    return totalGetMoney
        .multiply(bCimmissionRate)
        .setScale(OrdersConstant.SCALE,BigDecimal.ROUND_DOWN);
  }

  protected Orders saveOrUpdateOrders(Orders orders, Orders previousOrder){
    // 如果订单记录在数据库已经存在，那么更新订单信息，否则直接插入
    //&& !orders.getTkStatus().equals(previousOrder.getTkStatus())
    logger.debug("preciousOrders is : {}",previousOrder);
    if(previousOrder != null ){
      logger.debug("update orders");
      ordersMapper.updateByPrimaryKeySelective(orders);
    }else{
      logger.debug("insert orders");
      ordersMapper.insertSelective(orders);
    }
    return previousOrder;
  }

  protected abstract void createIncomeRecord(
      Orders orders, Long userId, Long parentUserId,
      Long parentPuserId, Orders previousOrders,
      CommissionFreezeLevelSettings freezeCommissionSettings
  );

  protected void insertUserIncome(
      Orders orders, Long userId, Long parentUserId, Long parentPuserId,
      CommissionFreezeLevelSettings freezeCommissionSettings
  ){
    BigDecimal userCommission = orders.getUserCommission();
    BigDecimal oneLevelCommission = orders.getOneLevelCommission();
    BigDecimal twoLevelCommission = orders.getTwoLevelCommission();
    // 往用户收益表插入记录
    // 1 购买用户本人
    Integer roadType = 0;
    insertUserIncome(orders,userCommission,userId,roadType,freezeCommissionSettings);
    // 如果属于活动订单,那么上级, 上上级佣金不算
    if(orders.getActivityId() != null){
      return;
    }
    // 2 推广人，即上级用户
    if(parentUserId != null){
      roadType = 1;
      insertUserIncome(orders,oneLevelCommission,parentUserId,roadType,freezeCommissionSettings);
      if(parentPuserId != null){
        roadType = 2;
        insertUserIncome(orders,twoLevelCommission,parentPuserId,roadType,freezeCommissionSettings);
      }
    }
  }

  protected void insertUserIncome(
      Orders orders,
      BigDecimal money,
      Long userId,
      Integer roadType,
      CommissionFreezeLevelSettings freezeCommissionSettings
  ){
    boolean freezeCommission = freezeCommissionSettings != null;
    UserIncome userIncome = userIncomeHelper.inserOrderCommissionIncome(orders,money,userId,roadType,freezeCommission);
    if(freezeCommissionSettings != null){
      incomeCommissionFreezeLevelHelper.insert(userIncome.getUserIncomeId(),
          freezeCommissionSettings.getId());
    }
  }

  protected void updateUserIncome(
      Orders orders,
      Long userId,
      Long parentUserId,
      Long parentPuserId,
      List<UserIncome> userIncomeList,
      Long tkStatus,
      CommissionFreezeLevelSettings freezeCommissionSettings
  ){
    BigDecimal userCommission = orders.getUserCommission();
    BigDecimal oneLevelCommission = orders.getOneLevelCommission();
    BigDecimal twoLevelCommission = orders.getTwoLevelCommission();
    // 往用户收益表插入记录
    // 1 购买用户本人
    UserIncome userIncome = getUserIncomeIdFromList(userIncomeList,userId);
    updateUserIncome(userIncome,userCommission,tkStatus,freezeCommissionSettings);
    // 如果属于活动订单,那么上级, 上上级佣金不算
    if(orders.getActivityId() != null){
      return;
    }
    // 2 推广人，即上级用户
    if(parentUserId != null){
      UserIncome parentIncome = getUserIncomeIdFromList(userIncomeList,parentUserId);
      updateUserIncome(parentIncome,oneLevelCommission,tkStatus,freezeCommissionSettings);
      if(parentPuserId != null){
        UserIncome parentPIncome = getUserIncomeIdFromList(userIncomeList,parentPuserId);
        updateUserIncome(parentPIncome,twoLevelCommission,tkStatus,freezeCommissionSettings);
      }
    }
  }

  private void updateUserIncome(
      UserIncome preIncome, BigDecimal money, Long tkStatus,
      CommissionFreezeLevelSettings freezeCommissionSettings
  ){
    UserIncome userIncome = new UserIncome();
    userIncome.setUserIncomeId(preIncome.getUserIncomeId());
    userIncome.setMoney(money);
    userIncome.setTkStatus(tkStatus);
    if(freezeCommissionSettings == null ){
      userIncome.setStatus(UserIncomeConstant.IS_PAID);
    } else {
      userIncome.setStatus(getIncomeStatusWhenUpdate(preIncome));
    }
    userIncome.setUpdateTime(DateUtil.getNowStr());
    logger.debug("update UserIncome is: {}",userIncome);
    userIncomeMapper.updateByPrimaryKeySelective(userIncome);
  }

  private UserIncome getUserIncomeIdFromList(List<UserIncome> userIncomeList,Long userId){

    logger.debug("userIncomeList is : {}",userIncomeList);
    for(int i = 0 ; i<userIncomeList.size() ; i++){
      Long incomeUserId = userIncomeList.get(i).getUserId();
      if(incomeUserId.equals(userId)){
        return userIncomeList.get(i);
      }
    }
    return null;
  }

  private Integer getIncomeStatusWhenUpdate(
      UserIncome preIncome){
    // 从付款进入到结算/完成，应该为冻结状态
    if (OrdersConstant.PAID_STATUS.equals(preIncome.getTkStatus())){
      return UserIncomeConstant.FREEZE;
    }
    // 如果先前是冻结状态或者付款状态，那么无需改变状态
    if (UserIncomeConstant.FREEZE == preIncome.getStatus() ||
        UserIncomeConstant.IS_PAID == preIncome.getStatus()
    ){
      return null;
    }
    return null;
  }

  protected CommissionFreezeLevelSettings getFreezeSettingsByMoney(BigDecimal money){
    Integer type = 0;
    List<CommissionFreezeLevelSettings> settingsList =
        commissionFreezeLevelSettingsMapper.selectByBeginAndEnd(money,type);
    if(!ListUtil.isEmptyList(settingsList)){
      return settingsList.get(0);
    }
    return null;
  }

  protected void checkNewUserTask(Long userId, Orders orders){
    // 获取之前完成的订单数
    Long count = ordersMapper.selectDoneOrdersCount(userId);
    logger.debug("user done orders count is : {}",count);
    // 如果之前没有订单在结算或者完成状态，那么进行新人用户奖励
    if (count == null || count == 0){
      // 获取新人用户奖励配置
      TaskSettings taskSettings = taskSettingsMapper.selectUseSettingsBySubType(
          TaskSettingsConstant.FIRST_ORDER
      );
      // 进行新人用户奖励
      if(taskSettings != null){
        UserIncome userIncome = UserIncomeBuilder.buildNotOrdersRelateUserIncome(
            UserIncomeConstant.FIRST_DONE_ORDER_AWARD_TYPE,
            UserIncomeConstant.UIT_AWARD_TYPE,
            Long.valueOf(taskSettings.getAwardNum()),
            userId
        );
        userIncomeMapper.insertSelective(userIncome);
        userHelper.pluUserVirtualMoneyByType(taskSettings,userId);
      }
    }
  }

  protected void checkAndAwardToUser(Orders orders){
    if (orders.getUserId() == null){
      logger.debug("orders userId is null");
      return;
    }
    User user = userMapper.selectById(orders.getUserId());
    if (user == null){
      logger.debug("checkAndAwardToUser user is null");
      return;
    }
    Long parentUserId = user.getParentUserId();
    Long userId = user.getUserId();
    if (parentUserId == null){
      logger.debug("parentUserId is null");
      return;
    }

    // 如果用户有上级
    if(parentUserId != null){
      logger.debug("parentUserId is : {}",parentUserId);
      int count = userIncomeMapper.selectInviteIncomeByUserId(parentUserId,userId);

      logger.debug("InviteIncome count for parentUserId and userId is :{},{},{}",parentUserId,userId,count);
      // 如果针对当前用户已经奖励过推广人,那么无需再进行奖励,否則繼續獎勵
      if(count <= 0){
        InviteSettings inviteSettings = inviteSettingsMapper.selectByPrimaryKey(1);
        String awardGradJson = inviteSettings.getAwardGradJson();
        String conditonJson = inviteSettings.getConditionJson();
        logger.debug("invite settings is : {}",inviteSettings);
        logger.debug("awardGradJson and conditonJson : {},{}",
            awardGradJson,conditonJson);
        Type type = new TypeToken<Map<String, AwardGradValue>>() {}.getType();
        Map<String, AwardGradValue> qwardGrad = gson.fromJson(awardGradJson,type);
        BigDecimal consumePrice = new BigDecimal(conditonJson);
        // 如果购买的金额大于设置的金额才算拉新成功
        if(orders.getAlipayTotalPrice().compareTo(consumePrice) >=0){
          int currentCount = userIncomeMapper.selectCountByUserIdAndType(parentUserId,UserIncomeConstant.INVITE_AWAED_TYPE);
          currentCount = currentCount + 1;
          logger.debug("currentCount is :{}",currentCount);
          AwardGradValue range1 = qwardGrad.get("1");
          AwardGradValue range2 = qwardGrad.get("2");
          AwardGradValue range3 = qwardGrad.get("3");
          // 确定奖励范围
          long awardNum  = 0L ;
          logger.debug("awardNum is : {}",awardNum);
          if(currentCount>=range1.getBegin() && currentCount<range1.getEnd()){
            awardNum = range1.getAward();
          }
          if(currentCount>=range2.getBegin() && currentCount<range2.getEnd()){
            awardNum = range2.getAward();
          }
          if(currentCount>=range3.getBegin() && currentCount<range3.getEnd()){
            awardNum = range3.getAward();
          }
          userMapper.plusUserUit(awardNum,parentUserId);
          Integer roadType = 1;
          UserIncome userIncome = UserIncomeBuilder.buildInviteUserIncome(orders,awardNum,parentUserId,roadType);
          logger.debug("UserIncome is : {}",userIncome);
          userIncomeMapper.insertSelective(userIncome);
        }
      }
    }
  }


  // 当订单进入到失效状态的时候, 如果收益记录的订单状态是结算/完成状态，并且已经到账,那么就减去之前给用户奖励的集分宝
  protected void deleteUserIncomeWhenOverDue(Orders orders){
    // 如果是失效订单，应该删除相应收益记录，并且相应减少用户集分宝
    List<UserIncome> userIncomeList = userIncomeMapper.seleteUserIncomeByTradeId(orders.getTradeId());
    if(userIncomeList != null){
      userIncomeList.forEach(userIncome -> {
        if(OrdersConstant.ACCOUNTING_STATUS.equals(orders.getTkStatus()) ||
            OrdersConstant.COMPLETE_STATUS.equals(orders.getTkStatus())){
          if(UserIncomeConstant.IS_PAID == userIncome.getStatus()){
            Long uit = DecimalUtil.convertMoneyToUit(userIncome.getMoney());
            userMapper.plusUserIntgeral(-uit,userIncome.getUserId());
          }
        }
      });
    }
    userIncomeMapper.deleteByTradeId(orders.getTradeId());
  }

  public String concatPid(Orders orders){
    StringBuilder builder = new StringBuilder();
    builder.append("mm_");
    builder.append("196240035");
    builder.append("_");
    builder.append(orders.getSiteId());
    builder.append("_");
    builder.append(orders.getAdzoneId());
    return builder.toString();
  }

  protected void countUserOrdersNum(Orders orders){
    if(orders.getUserId() != null){
      userMapper.plusOrdersNumByOne(orders.getUserId());
      if(orders.getPromoterId() != null &&
          !orders.getUserId().equals(orders.getPromoterId())){
        userMapper.plusOrdersNumByOne(orders.getPromoterId());
      }
    }else{
      if(orders.getPromoterId() != null){
        userMapper.plusOrdersNumByOne(orders.getPromoterId());
      }
    }
  }
}
